import { initSystemInfo, logout as _logout } from '@common/helper/system';
import { loadHistoryMenus, loadMenus, loadStarMenus, loadTopMenus } from '@/data/api/menu';
import { useMenuStore } from '@/stores/menu-store';
import { useGlobalStore } from '@common/store/global-store';
import { useAdminStore } from '@/stores/admin-store';
import { loadUserConfig } from '@/data/api/setting';
import { useUserConfigStore } from '@/stores/user-config-store';
import { checkThirdToken } from './third';
/**
 * 初始化系统数据
 *
 * @export
 * @param {*} router
 * @param {*} route
 * @return {*}
 */
export function initSystem(router, route) {
  const globalStore = useGlobalStore();
  const adminStore = useAdminStore();

  // 已经初始化数据，设置默认菜单
  if (adminStore.init) {
    // menuStore.setActiveMenu(route.meta?.menu);
    return Promise.resolve();
  }

  // 初始系统数据，菜单数据，路由数据
  return checkThirdToken()
    .then(() => initSystemInfo())
    .then(() => Promise.all([initMenus(), initUserConfig()]))
    .then(() => {
      globalStore.init = true;
      adminStore.login();
      return route.fullPath;
    });
}
/**
 * 初始化用户态数据
 * @returns
 */
function initUserConfig() {
  const userConfigStore = useUserConfigStore();
  return loadUserConfig().then((data) => {
    userConfigStore.init(data);
  });
}
/**
 * 初始化菜单
 * @returns
 */
function initMenus() {
  const menuStore = useMenuStore();
  // 初始系统数据，菜单数据，路由数据
  return Promise.all([loadMenus(), loadTopMenus(), loadStarMenus(), loadHistoryMenus()]).then(
    ([menus, topMenus, starMenus, historyMenus]) => {
      menuStore.parseMenus([menus]);
      menuStore.parseMenus(topMenus, 'top');
      menuStore.parseMenus(starMenus, 'star');
      menuStore.parseMenus(historyMenus, 'history');
      menuStore.inited();
    },
  );
}
/**
 * 退出
 */
export function logout() {
  const adminStore = useAdminStore();
  adminStore.logout();
  _logout();
}

/* 
    // 设置激活菜单，目前菜单路由格式为：/main/topMenuId/menuId
    const paths = route.fullPath.split('/');
    let menu = menuStore.getMenu(paths[3]); // 提取菜单ID
    if (!menu) {
      // 默认打开第一个顶部菜单，第一个左侧菜单
      const defaultTopMenu = menuStore.topMenus.values().next().value;
      if (defaultTopMenu.siderMenu) {
        menu = menuStore.getMenu(defaultTopMenu.siderMenu.defaultSelectedKey);
      } else {
        menu = defaultTopMenu;
      }
    }
    // 系统数据初始化成功
    globalStore.init = true;
    // 返回系统登录成功后的跳转路由
    return menu ? { name: menu.id } : route.fullPath; */
